/* $Id: qx-plugins.js 10 2012-04-08 15:34:15Z zhaofang123 $ */

qx.backdrop = function(){
	var el = new Element('div', { 'class':'backdrop' }).inject(document.body);
	el.setStyles({
		'opacity': 0.6
	});
	return el;
}

qx.Modal = function(headText, bodyText, btnEvent){
	var dbEl = qx.backdrop();
	var self = this;
	var baseHtml = ['<div class="modal-header"><a class="close" href="#" title="关闭">&times;</a><h3>' + (headText||'&nbsp;') + '</h3></div>'];
	baseHtml.push('<div class="modal-body"><p>' + (bodyText||'&nbsp;') + '</p></div>');
	baseHtml.push('<div class="modal-footer"><a class="btn btn-primary">确定</a>&nbsp;<a class="btn -close">取消</a></div>');
	var el = new Element('div', { 'class':'modal', 'html':baseHtml.join('') });
	this.element = el;
	$(document.body).adopt(el);
	qx.center(el);
	qx.focus(el);
	el.getElement('.close').addEvent('click', function(){ self.close() });
	el.getElement('.-close').addEvent('click', function(){ self.close() });
	el.getElement('.btn-primary').addEvent('click', function(){ if (btnEvent) btnEvent(self); });
	
	var closeByKey = function(event){ if (event.key == 'esc') self.close(); }
	$(document.body).addEvent('keydown', closeByKey);
	// 关闭
	this.close = function(){
		self.element.destroy();
		dbEl.destroy();
		$(document.body).removeEvents(closeByKey);
	}
}

// 加载条
qx.Progress = function(text, loadTime){
	var dbEl = qx.backdrop();
	var self = this;
	var baseHtml = ['<div class="progress-text">'+ (text||'正在处理') +'</div>'];
	baseHtml.push('<div class="progress-bar"><div class="progress-bar-load"></div></div>');
	var el = new Element('div', { 'class':'progress', 'html':baseHtml.join('') });
	this.element = el;
	loadTime = loadTime || 0;
	if (loadTime > 0){
		var bar = el.getElement('.progress-bar-load').swapClass('progress-bar-load', 'progress-bar-pc');
		bar.set('tween', { 'duration':loadTime, 'unit':'%' });
		bar.tween('width', [0, 100]);
		this.__loadTimer = setTimeout(function(){
			bar.swapClass('progress-bar-pc', 'progress-bar-load');
		}, loadTime + 25);
	}
	$(document.body).adopt(el);
	qx.center(el);
	qx.focus(el);
	
	// 关闭
	this.close = function(){
		if (loadTime > 0){
			var barPc = el.getElement('.progress-bar-pc');
			if (barPc){
				clearTimeout(self.__loadTimer);
				barPc.get('tween').cancel();
				barPc.setStyle('width', '100%');
			}
			setTimeout(function(){
				self.element.destroy();
				dbEl.destroy();
			}, 100);
		} else {
			self.element.destroy();
			dbEl.destroy();
		}
	}
};